package algorithm

import "fmt"

// 股票买卖问题
// 仅买一次
func onlyOne(arr []int) (first, last int, profit int) {
	first, last = 0, 0
	if len(arr) < 2 {
		return -1, -1, 0
	}
	minPrice, profit, last := arr[0], arr[1]-arr[0], 1
	tmp := 0
	for i := 2; i < len(arr); i++ {
		if arr[i] < minPrice {
			tmp = i
		}
		if arr[i]-minPrice > profit {
			profit = arr[i] - minPrice
			first, last = tmp, i
		}
	}
	if profit < 0 {
		return -1, -1, 0
	}
	return first, last, profit
}
func RunBuyStockPrice() {
	case1 := []int{1, 2, 34, 56, 6, 100}
	case2 := []int{5, 4, 3, 2, 1}
	case3 := []int{1, 2, 3, 4, 5, 0, 1}
	case4 := []int{1, 100, 34, 56, 6, 7}
	fmt.Println("仅买卖一次股票的收益，以及买卖天数")
	fmt.Println(case1)
	fmt.Println(onlyOne(case1))
	fmt.Println(case2)
	fmt.Println(onlyOne(case2))
	fmt.Println(case3)
	fmt.Println(onlyOne(case3))
	fmt.Println(case4)
	fmt.Println(onlyOne(case4))
	fmt.Println("任意买卖股票的收益")
	case5 := []int{1, 2, 34, 0, 5, 6, 100}
	case6 := []int{1, 1000, 34, 0, 5, 6, 100}
	fmt.Println(case5)
	fmt.Println(buyAnyWay(case5))
	fmt.Println(case6)
	fmt.Println(buyAnyWay(case6))
}

func buyAnyWay(arr []int) (profit int) {
	if len(arr) < 2 {
		return 0
	}
	stock := arr[0]
	profit = 0
	tmp := 0
	for i := 1; i < len(arr); i++ {
		if arr[i]-stock > profit {
			profit = arr[i] - stock
			stock = tmp
		}
		if arr[i] < stock {
			tmp = i
		}
	}
	return profit
}
